import { component$, useSignal } from '@builder.io/qwik';
import { Form, Link } from '@builder.io/qwik-city';
import { type PostCollection } from '@prisma/client';
import { cn } from '~/components/cn';
import Button from '~/components/ui/Button';
import Input from '~/components/ui/Input';
import { ListItem } from '~/components/ui/List';

type PostCollectionItemProps = {
  collection: PostCollection;
};

const PostCollectionItem = component$<PostCollectionItemProps>(({ collection }) => {
  const editable = useSignal(false);


  return (
    <ListItem class={cn('group/post-collection flex justify-between', editable.value && 'p-1')}>
      {editable.value ? (
        <Form
          class="w-full"
          // action={updateCollectionAction}
          spaReset
          onSubmitCompleted$={() => {
            editable.value = false;
          }}
        >
          <Input name="id" type="hidden" value={collection.id.toString()} />
          <Input name="title" sizing="sm" value={collection.title} block />
          <div class="mt-1 text-right">
            <Button sizing="sm" onClick$={() => (editable.value = false)}>
              取消
            </Button>
            <Button type="submit" sizing="sm">
              保存
            </Button>
          </div>
        </Form>
      ) : (
        <>
          <span class="cursor-pointer">
            <Link href={`/me/post-collections/${collection.id.toString()}`}>{collection.title}</Link>&nbsp;
            <span
              class="hidden group-hover/post-collection:cursor-pointer group-hover/post-collection:inline"
              onClick$={() => (editable.value = true)}
            >
              🖍
            </span>
          </span>
          <span
            class="ml-1 hidden group-hover/post-collection:cursor-pointer group-hover/post-collection:inline"
            // onClick$={async () => await deleteCollectionAction.submit({ id: collection.id.toString() })}
          >
            ×
          </span>
        </>
      )}
    </ListItem>
  );
});

export default component$<{ collections: PostCollection[] }>(({ collections }) => {
  return (
    <>
      {collections.map((it) => (
        <PostCollectionItem key={it.id.toString()} collection={it} />
      ))}
    </>
  );
});
